package com.asset.action;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.asset.pojo.Asset;
import com.asset.pojo.AssetOperate;
import com.asset.pojo.AssetUseHistory;
import com.asset.pojo.Department;
import com.asset.pojo.Status;
import com.asset.pojo.User;
import com.asset.utils.*;
import com.asset.webBean.AssetWeb;
import org.apache.poi.ss.usermodel.Workbook;
import java.io.*;
import java.net.*;
import java.text.SimpleDateFormat;
import java.util.*;

public class AssetAction extends BaseAction {

	private static final long serialVersionUID = 1L;
	private String text;
	private OutputStream output;
	private File file;
	private String fileName;
	private String temp;
	private List<Asset> assetLists;
	private List<Asset> pdLists;
	private List<Asset> unPdLists;
	private AssetWeb assetWeb;
	private int pdStatus;
	private Asset asset;
	private User loginUser;
	private AssetOperate aote;
	private AssetUseHistory assetUseHistory;
	private List<AssetUseHistory> assetUseHistoryList;
	private int id;
	private Short optestate;
	private Short state;
	private Date receiveTime;
	private Date revertTime;
	private String ids;
	private String equipIdentifier;
	private String itCode;
	private String operaRes; // 1 操作成功，2 操作失败，即定义的是ajax请求成功后服务器向前段发送的数据
	private String url = "";
	private List<String> QRcodeUrl; // 二维码存放数组
	private String identifer;
	private String[] checkedIds;
	private static int pigeNum = 15;
	// 总页数
	private int pageSizeALL;
	// 当前页
	private int pageSizeCurr = 1;
	// 所有记录数目
	private int pageNumAll;
	// 显示导航数组
	private List<Integer> pagingArr;
	// 查询总数量;
	private int querySum;
	// 查询的用户名
	private String queryUserName;
	private Long userId;
	private List<User> userList;
	private JSONArray jsonArray;
	private JSONObject jsonObject;
	private Integer start;
	private Integer length;
	private Integer draw;
	private Short equipGenre;
	private Short status;
	private Date buyTime1;
	private Date buyTime2;
	private Date useTime1;
	private Date useTime2;
	private Map<String, Object> dataMap;

	private JSONObject operaRem;
	private JSONArray departmentArr;
	private String departQueryName;

	// 返回结果集信息
	public List<Department> useDepartList;
	public List<Department> departmentList;

	//查询登录用户
	{
		loginUser = (User) getSession().getAttribute(UserKEY);	   
		
	}
	// 获取端口和IP
	{
		Enumeration<NetworkInterface> allNetInterfaces;
		try {
			allNetInterfaces = NetworkInterface.getNetworkInterfaces();// 获取此台机器上的所有网络接口
			InetAddress ip = null;
			while (allNetInterfaces.hasMoreElements()) {
				NetworkInterface netInterface = (NetworkInterface) allNetInterfaces.nextElement();

				Enumeration<InetAddress> addresses = netInterface.getInetAddresses();
				while (addresses.hasMoreElements()) {
					ip = (InetAddress) addresses.nextElement();
					if (ip != null && ip instanceof Inet4Address) {
						url = "http://" + ip.getHostAddress() + ":8080/getAssetMessage.action";
					}
				}
			}
		} catch (SocketException e) {
			e.printStackTrace();
		}
	}

	// 格式转换
	private AssetWeb passAssetWeb(Asset a) {
		
			AssetWeb aw = new AssetWeb();
			SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			aw.setId(a.getId());
			aw.setEquipIdentifier(a.getEquipIdentifier());
			aw.setItCode(a.getItCode());
			if (a.getEquipGenre() != null) {
				aw.setEquipGenre(Asset.EquipGenre.getName(a.getEquipGenre()));
			}
			aw.setEquipName(a.getEquipName());
			aw.setEquipModel(a.getEquipModel());
			aw.setEquipBrand(a.getEquipBrand());
			aw.setUsePerson(a.getUsePerson());
			aw.setUseDepart(a.getUseDepart());
			aw.setEquipLocation(a.getEquipLocation());
			aw.setEquipAttach(a.getEquipAttach());
			aw.setCondition(a.getCondition());
			aw.setAssetAllocation(a.getAssetAllocation());
			if (a.getBuyTime() != null) {
				aw.setBuyTime(sdf2.format(a.getBuyTime()));
			}
			if(a.getAssignTime() !=null){
				aw.setAssignTime(sdf2.format(a.getAssignTime()));
			}else{
				aw.setAssignTime(null);
			}
			if(a.getReceiveTime() != null){
				aw.setReceiveTime(sdf2.format(a.getReceiveTime()));
			}else{
				aw.setReceiveTime(null);
			}
			if (a.getModifyTime() != null) {
				aw.setModifyTime(sdf2.format(a.getModifyTime()));
			}
			if (a.getIfPd() != null) {
				aw.setIfPd(Asset.IfPd.getName(a.getIfPd()));
			}
			aw.setRemarks(a.getRemarks());
			if (a.getStatus() != null) {
				aw.setStatus(Asset.Status.getName(a.getStatus()));
			}
			aw.setLastUser(a.getLastUser());
			return aw;
	}

	// 查看资产明细
	public String assetInfo() {
		
		try {
			if (id == 0) {
				asset = new Asset();
				getSession().setAttribute("opteStatus", 0);
			} else {
				asset = assetService.getAssetByPrivateKey(id);
			    state = asset.getStatus();
				asset.setStatus(state);
				getSession().setAttribute("opteStatus",1);
				getSession().setAttribute("identifier",asset.getEquipIdentifier());
				getSession().setAttribute("equipCode",asset.getItCode());
				assetUseHistoryList = assetUseHistoryService.getHistoryByKey(id);
				for (AssetUseHistory auhy : assetUseHistoryList) {
					if(auhy.getAssetSign() == 0){						
						assetUseHistory = auhy;	
					    break;
					}else{
						continue;
					}
				}
			}
			
			assetWeb = passAssetWeb(asset);
		} catch (Exception e) {
			e.printStackTrace();
			return "sysError";
		}
		return "success";
	}

	 //添加时查询资产编号和IT编号是否存在
    public String listUserDataCheck(){
        int sessStatus =  (int) getSession().getAttribute("opteStatus");  
        String sessIdenti = (String) getSession().getAttribute("identifier");
        String sessItcode = (String) getSession().getAttribute("equipCode");      
    	int count = 0;
    	if(sessStatus == 0){
    		if(equipIdentifier != null){
    			asset = assetService.getAssetByIdentifer(equipIdentifier);
    			if(asset != null){
    				count = 1;
    			}
    		}
    		if(itCode != null){
    			asset = assetService.getAssetByItCode(itCode);
    			if(asset != null){
    				count = 1;
    			}
    		}
    	}else{
    		if(equipIdentifier != null){
    			if(equipIdentifier.equals(sessIdenti)){
    				count = 0;
    			}else if(equipIdentifier != sessIdenti){
    				asset = assetService.getAssetByIdentifer(equipIdentifier);
    				if(asset != null){
        				count = 1;
        			}
    			}
    		}
    		if(itCode != null){
    			if(itCode.equals(sessItcode)){
    				count = 0;
    			}else if(itCode != sessItcode){
    				asset = assetService.getAssetByItCode(itCode);
    				if(asset != null){
        				count = 1;
        			}
    			}
    		}
    	}
		
			operaRem = new JSONObject();
			if(count == 1){
				operaRem.put("error","该编号已经被使用");
			}else{
				operaRem.put("ok","该编号可以使用");
			}
		return SUCCESS;		
	}
    
	// 添加修改页面
	public String toAddAsset() {
		// 返回一个方法，即调用上面的assetInfo()方法，该方法返回success或sysError
		return assetInfo();
	}

	// 添加资产
	public String addAsset() {         
     			// 提交的同时，将最后修改时间修改为当前时间
     			asset.setModifyTime(new Date());
     			asset.setLastUser(loginUser.getName());
     			assetService.insert(asset);
     			
     			aote = new AssetOperate();
     			aote.setOptePerson(loginUser.getName());
     			aote.setOpteGenre(AssetOperate.OpteGenre.getValue("添加"));
     			aote.setEquipIdentifier(asset.getEquipIdentifier());
     			aote.setEquipName(asset.getEquipName());
     			aote.setEquipModel(asset.getEquipModel());
     			aote.setEquipBrand(asset.getEquipBrand());
     			aote.setOpteTime(new Date());
     			assetopteService.insertAssetOpte(aote);
     			operaRes = "1";	
    			getSession().setAttribute("tip", "添加成功");			
		return SUCCESS;
	}

	// 修改资产
	public String modifyAsset() {
			if(asset.getStatus() == null){
				asset.setModifyTime(new Date());
				asset.setLastUser(loginUser.getName());
				assetService.updateByKey(asset);
			}else{
				asset.setAssignTime(null);
				asset.setReceiveTime(null);
				asset.setUsePerson(null);
				asset.setModifyTime(new Date());
				asset.setLastUser(loginUser.getName());
				assetService.updateByPrivateKey(asset);
			}

			aote = new AssetOperate();
			aote.setOptePerson(loginUser.getName());
			aote.setOpteGenre(AssetOperate.OpteGenre.getValue("修改"));
			aote.setEquipIdentifier(asset.getEquipIdentifier());
			aote.setEquipName(asset.getEquipName());
			aote.setEquipModel(asset.getEquipModel());
			aote.setEquipBrand(asset.getEquipBrand());
			aote.setOpteTime(new Date());
			assetopteService.insertAssetOpte(aote);
						
			assetUseHistoryList = assetUseHistoryService.getHistoryByKey(id);
			for (AssetUseHistory auhy : assetUseHistoryList) {
				if(auhy.getAssetSign() == 0){						
					auhy.setReceiveTime(receiveTime);
					auhy.setRevertTime(revertTime);								
					if(optestate == 0){
						assetUseHistory.setEquipState((short) 1);						
				    }else{
				    	auhy.setEquipState(optestate);
				    }
					assetUseHistoryService.updateAssetHistory(auhy);		
				break;
				}else{
					continue;
				}
			}
			operaRes = "1";	
			getSession().setAttribute("tip", "修改成功");
		return SUCCESS;
	}
	
	// 分配设备
	public String assignAsset() {	
		
			Asset asset = assetService.getAssetByPrivateKey(id);
			User user = userService.getUserById(userId);
			asset.setUsePerson(user.getCode());
			asset.setStatus(Asset.Status.Assigned.value);
			asset.setModifyTime(new Date());
			asset.setAssignTime(new Date());
			asset.setLastUser(loginUser.getName());
			assetService.updateByPrivateKey(asset);
			
			aote = new AssetOperate();
			aote.setOptePerson(loginUser.getName());
			aote.setOpteGenre(AssetOperate.OpteGenre.getValue("分配"));
			aote.setEquipIdentifier(asset.getEquipIdentifier());
			aote.setEquipName(asset.getEquipName());
			aote.setEquipModel(asset.getEquipModel());
			aote.setEquipBrand(asset.getEquipBrand());
			aote.setOpteTime(new Date());
			assetopteService.insertAssetOpte(aote);
			
			assetUseHistoryList = assetUseHistoryService.getHistoryByKey(id);
			for (AssetUseHistory auhy : assetUseHistoryList) {
				if(auhy.getAssetSign() == 0){
					auhy.setAssetSign(1);
					assetUseHistoryService.updateAssetHistory(auhy);
					break;
				}else{
					continue;
				}
			} 		
			assetUseHistory = new AssetUseHistory();
			assetUseHistory.setUsePerson(user.getName());
			assetUseHistory.setUserCode(user.getCode());
			assetUseHistory.setAssignTime(new Date());
			assetUseHistory.setAssetId(asset.getId());
			assetUseHistory.setAssetSign(0);
			assetUseHistoryService.addAssetHistory(assetUseHistory);
			operaRes = "1";	
		return SUCCESS;
	}

	// 领用设备
	public String receiveAsset() {
	
			asset = assetService.getAssetByPrivateKey(id);

			asset.setStatus(Asset.Status.Using.value);
			asset.setModifyTime(new Date());
			asset.setReceiveTime(receiveTime);
			asset.setLastUser(loginUser.getName());
			assetService.updateByPrivateKey(asset);
			
			aote = new AssetOperate();
			aote.setOptePerson(loginUser.getName());
			aote.setOpteGenre(AssetOperate.OpteGenre.getValue("领用"));
			aote.setEquipIdentifier(asset.getEquipIdentifier());
			aote.setEquipName(asset.getEquipName());
			aote.setEquipModel(asset.getEquipModel());
			aote.setEquipBrand(asset.getEquipBrand());
			aote.setOpteTime(new Date());
			assetopteService.insertAssetOpte(aote);
			
			assetUseHistoryList = assetUseHistoryService.getHistoryByKey(id);
			for (AssetUseHistory auhy : assetUseHistoryList) {
				if(auhy.getAssetSign() == 0){
					auhy.setReceiveTime(receiveTime);
					assetUseHistoryService.updateAssetHistory(auhy);
					
					break;
				}else{
					continue;
				}
			}
			operaRes = "1";	
		return SUCCESS;
	}

	// 归还设备
	public String revertAsset() {
            
			asset = assetService.getAssetByPrivateKey(id);
			// 归还时将名字置为空，修改时间置为当前时间
			asset.setAssignTime(null);
			asset.setReceiveTime(null);
			asset.setModifyTime(new Date());
			asset.setUsePerson(null);
			if(optestate == 2){
				asset.setStatus((short) 4);
			}else if(optestate == 3){
				asset.setStatus((short) 5);
			}else{
				asset.setStatus((short) 1);
			}
			asset.setLastUser(loginUser.getName());
			assetService.updateByPrivateKey(asset);

			aote = new AssetOperate();			              
			aote.setOptePerson(loginUser.getName());
			aote.setOpteGenre(AssetOperate.OpteGenre.getValue("归还"));
			aote.setEquipIdentifier(asset.getEquipIdentifier());
			aote.setEquipName(asset.getEquipName());
			aote.setEquipModel(asset.getEquipModel());
			aote.setEquipBrand(asset.getEquipBrand());
			aote.setOpteTime(new Date()); 
			assetopteService.insertAssetOpte(aote);
			
			assetUseHistoryList = assetUseHistoryService.getHistoryByKey(id);
			for (AssetUseHistory auhy : assetUseHistoryList) {
				if(auhy.getAssetSign() == 0){
				    auhy.setRevertTime(revertTime);	
				    if(optestate == 0){
				    	auhy.setEquipState((short) 1);
				    }else{
				    	 auhy.setEquipState(optestate);
				    }				   
					assetUseHistoryService.updateAssetHistory(auhy);	
					break;
				}else{
					continue;
				}
			}
			operaRes = "1";				
		
		return "success";

	}

	// 删除单个
	public String deleteAsset() {
		  
			asset = assetService.getAssetByPrivateKey(id);
			aote = new AssetOperate();
			aote.setOptePerson(loginUser.getName());
			aote.setOpteGenre(AssetOperate.OpteGenre.getValue("删除"));
			aote.setEquipIdentifier(asset.getEquipIdentifier());
			aote.setEquipName(asset.getEquipName());
			aote.setEquipModel(asset.getEquipModel());
			aote.setEquipBrand(asset.getEquipBrand());
			aote.setOpteTime(new Date());
			assetopteService.insertAssetOpte(aote);
			
			assetService.delectByPrivateKey(id);			
			operaRes = "1";
		
		return "success";
	}

	// 删除多个
	public String deleteAssetMany() {
		 
			// 因为页面传过来的数据是字符串，所以用正则表达式将其转成数组			
			String[] assetId = ids.split(",");
			if (assetId.length == 1 && "".equals(assetId[0])) {
				getSession().setAttribute("tip", "请选择需要删除的信息");
				operaRes = "1";
				
			} else {
				for (String as : assetId) {
					asset = assetService.getAssetByPrivateKey(Integer.parseInt(as));
					aote = new AssetOperate();
					aote.setOptePerson(loginUser.getName());
					aote.setOpteGenre(AssetOperate.OpteGenre.getValue("删除"));
					aote.setEquipIdentifier(asset.getEquipIdentifier());
					aote.setEquipName(asset.getEquipName());
					aote.setEquipModel(asset.getEquipModel());
					aote.setEquipBrand(asset.getEquipBrand());
					aote.setOpteTime(new Date());
					assetopteService.insertAssetOpte(aote);					
					assetService.delectByPrivateKey(Integer.parseInt(as));
					operaRes = "1";
					getSession().setAttribute("tip", "删除成功");
				}
			}
			
		return SUCCESS;
	}

	// 资产页面数据加载
	public String listAllAssetData() {
		statusService.getStatus(); // 注意：此处是盘点状态
		List<Asset> asl = new ArrayList<Asset>();
		pageNumAll = 0;	
		asl = assetService.listAssetAllPage(temp, start, length, equipGenre, status,buyTime1,buyTime2,useTime1,useTime2);	
		pageNumAll = assetService.listAssetAllPage(temp, null, null, equipGenre, status,buyTime1,buyTime2,useTime1,useTime2).size();
		dataMap = new HashMap<String, Object>();
		dataMap.put("draw", draw);
		dataMap.put("recordsTotal", pageNumAll);
		dataMap.put("data", passArray(asl));
		dataMap.put("recordsFiltered", pageNumAll);
		return "success";
	}

	// 刷新资产页面
	public String listAssetAll() {
		try {
			getSession().setAttribute("colId", 1);
			temp = getTemp();
			if (getSession().getAttribute("tip") != null && getSession().getAttribute("tip") != "") {
				tip = (String) getSession().getAttribute("tip");
				getSession().setAttribute("tip", null);
			}
			;
		} catch (Exception e) {
			e.printStackTrace();
			return "sysError";
		}

		return SUCCESS;
	}

	public String editPdAsset() {
		Status status = new Status();
		status.setPdStatus(pdStatus);
		if (pdStatus == 1) {
			statusService.updateSataus(status);
		} else {
			statusService.updateSataus(status);
			assetService.exitIfPd(2);
		}
		return SUCCESS;
	}

	public String toPdNotAsset() {
		Status s = statusService.getStatus();
		pdLists = new ArrayList<Asset>();
		unPdLists = new ArrayList<Asset>();
		pdStatus = s.getPdStatus();
		if (pdStatus == 1) {// 如果开启盘点
			// unPdLists=assetService.listUnPd();
			pageNumAll = unPdLists.size();
		}
		return SUCCESS;
	}

	public String listPdNoAssetData() {
		Status s = statusService.getStatus();
		pdLists = new ArrayList<Asset>();
		unPdLists = new ArrayList<Asset>();
		pdStatus = s.getPdStatus();
		pageNumAll = 0;
		if (pdStatus == 1) {// 如果开启盘点
			try {
				unPdLists = assetService.listUnPd(temp, start, length,null, null,null, null);
			} catch (Exception e) {
				e.printStackTrace();
			}
			pageNumAll = assetService.listUnPd(temp, null, null,null, null,null, null).size();
		}
		dataMap = new HashMap<String, Object>();
		dataMap.put("draw", draw);
		dataMap.put("recordsTotal", pageNumAll);
		dataMap.put("data", passArray(unPdLists));
		dataMap.put("recordsFiltered", pageNumAll);
		return SUCCESS;
	}

	public String toPdAlreadyAsset() {
		Status s = statusService.getStatus();
		pdLists = new ArrayList<Asset>();
		unPdLists = new ArrayList<Asset>();
		pdStatus = s.getPdStatus();
		if (pdStatus == 1) {// 如果开启盘点
			pdLists = assetService.listPd(null, null, null,null, null,null, null);
			pageNumAll = pdLists.size();
		}
		return SUCCESS;
	}

	public String listPdAssetData() {
		Status s = statusService.getStatus();
		pdLists = new ArrayList<Asset>();
		pdStatus = s.getPdStatus();
		pageNumAll = 0;
		if (pdStatus == 1) {// 如果开启盘点
			try {
				pdLists = assetService.listPd(null, start, length,null, null,null, null);
			} catch (Exception e) {
				e.printStackTrace();
			}
			pageNumAll = assetService.listPd(null, null, null,null, null,null, null).size();
		}
		dataMap = new HashMap<String, Object>();
		dataMap.put("draw", draw);
		dataMap.put("recordsTotal", pageNumAll);
		dataMap.put("data", passArray(pdLists));
		dataMap.put("recordsFiltered", pageNumAll);
		return SUCCESS;
	}

	public String getAssetMessage() {
		try {
			asset = assetService.getAssetByPrivateKey(id);
			if (null == asset) {
				asset = new Asset();
				tip = "数据为空，可能已经被删除";
			} else {
				Status s = statusService.getStatus();
				pdStatus = s.getPdStatus();
				if (pdStatus == 1) {
					asset.setIfPd((short) 1);
					assetService.updateByPrivateKey(asset);
					tip = "盘点成功";
				} else {

				}
			}
			assetWeb = passAssetWeb(asset);
			departmentList = departService.listDepart(null);
		} catch (Exception e) {
			e.printStackTrace();
			getSession().setAttribute("e", e.getMessage());
			return "sysError";
		}
		return SUCCESS;
	}

	// 产生二维码
	public String genQRcode() {

		try {
			QRcodeUrl = new ArrayList<String>();

			if (checkedIds != null) {
				for (String as : checkedIds) {
					Asset asset = assetService.getAssetByPrivateKey(Integer.parseInt(as));
					if (asset != null) {
						identifer = asset.getEquipIdentifier();
					}
					QRcodeUrl.add("/asset/getQRcode.action?text=" + url + "?id=" + as + "&&identifer=" + identifer);
				}
			}

		} catch (Exception e) {
			e.printStackTrace();
			getSession().setAttribute("e", e.getMessage());
			return "sysError";
		}

		return SUCCESS;
	}

	public String getQRcode() {

		try {	
			output = getResponse().getOutputStream();
			CodeCreator.createCodeImage(text, null, "    资产编号:" + identifer,output);
			output.flush();
			output.close();
		} catch (Exception e) {
			e.printStackTrace();
			getSession().setAttribute("e", e.getMessage());
			return "sysError";
		}
		return null;
	}

	public String listUserData() {
		
		// 通过名字将该用户的所使用的所有设备查询
		List<User> userData = userService.listUser(queryUserName, null, null, null,null,null);
		jsonArray = new JSONArray();
		for (User u : userData) {
			JSONObject userObj = new JSONObject();
			userObj.put("id", u.getId());
			userObj.put("text", u.getName());
			jsonArray.add(userObj);
		}
		return SUCCESS;
	}

	// 资产列表数据加载格式
	private JSONArray passArray(List<Asset> asl) {
		JSONArray ja = new JSONArray();
		SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		for (Asset as : asl) {
			JSONObject jo = new JSONObject();
			jo.put("id", as.getId());
			jo.put("equipIdentifier", as.getEquipIdentifier());
			if (as.getEquipGenre() != null) {
				jo.put("equipGenre", Asset.EquipGenre.getName(as.getEquipGenre()));
			}
			jo.put("equipName", as.getEquipName());
			jo.put("equipModel", as.getEquipModel());
			if(as.getUsePerson() == null){
				jo.put("usePerson", as.getUsePerson());
			}else{
				user = userService.getUserByCode(as.getUsePerson());				
				jo.put("usePerson", user.getName());
			}
			jo.put("useDepart", as.getUseDepart());
			if (as.getEquipLocation() != null) {
				jo.put("equipLocation", as.getEquipLocation());
			}
			if (as.getStatus() != null) {
				jo.put("status", Asset.Status.getName(as.getStatus()));
			}
			jo.put("assetAllocation", as.getAssetAllocation());
			if (as.getBuyTime() != null) {
				jo.put("buyTime", sdf2.format(as.getBuyTime()));
			}
			if (as.getAssignTime() != null) {
				jo.put("assignTime", sdf2.format(as.getAssignTime()));
			}
			if (as.getReceiveTime() != null) {
				jo.put("receiveTime", sdf2.format(as.getReceiveTime()));
			}
			if (as.getModifyTime() != null) {
				jo.put("lastTime", sdf2.format(as.getModifyTime()));
			}
			jo.put("remarks", as.getRemarks());
			ja.add(jo);
		}
		return ja;
	}

	// 资产信息批量添加
	public String addByFile() {
		try {
			if (!(fileName.endsWith("csv") || fileName.endsWith("xls"))) {
				getSession().setAttribute("tip", "失败，目前仅支持csv和xls格式");
			} else {				
				List<List<String>> lls = new ArrayList<>();
				if(fileName.endsWith("csv")){
					InputStream fs = new FileInputStream(file);
					InputStreamReader fsr = new InputStreamReader(fs, "GBK");
					lls = CsvUtil.readCSVFile(fsr);
				}else{
					lls = XlsUtil.readXLSFile(file,0);
				}
				// 注意点：csv
				// 顺序：资产编号，IT编号，资产状态，设备类别，设备名称，设备型号，设备品牌，使用人员，使用部门，使用地点，所属地点，购买时间，分配时间，领用时间,最后修改时间，备注,ifPd
				List<Asset> assetList = assetService.listAssetAllPage(null, null, null, null, null,null,null,null,null);
				
				int k = 0;
				for (int i = 1; i < lls.size(); i++) {
					List<String> ls = lls.get(i);
					int count = 0 ;
					for (int j = 0; j < assetList.size(); j++) {
						if(assetList.get(j).getEquipIdentifier().equals(ls.get(0)) || assetList.get(j).getItCode().equals(ls.get(1))){
							count++;
							break;
						}
					}
					k = count;
					getSession().setAttribute("tip", "录入失败");
				}
				
				if(k == 0){
					for (int i = 1; i < lls.size(); i++) {
					Asset a = new Asset();
					List<String> ls = lls.get(i);
					SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
					for (int j = 0; j < assetList.size(); j++) {						
						if(assetList.get(j).getEquipIdentifier().equals(ls.get(0))){																									
						}
						else{
							a.setEquipIdentifier(ls.get(0));
						}
					}	
					
					if (ls.get(0) != null && !ls.get(0).equals("")) {
						a.setEquipIdentifier(ls.get(0));
					}					
					if (ls.get(1) != null && !ls.get(1).equals("")) {
						for (int j = 0; j < assetList.size(); j++) {			
							if(assetList.get(j).getItCode().equals(ls.get(1))){								
								break;
							}
							else{
								a.setItCode(ls.get(1));
							}
						}							
					}
					if (ls.get(2) != null && !ls.get(2).equals("")) {
						a.setStatus(Asset.Status.getValue(ls.get(2)));
					}
					if (ls.get(3) != null && !ls.get(3).equals("")) {
						a.setEquipGenre(Asset.EquipGenre.getValue(ls.get(3)));
					}
					if (ls.get(4) != null && !ls.get(4).equals("")) {
						a.setEquipName(ls.get(4));
					}
					if (ls.get(5) != null && !ls.get(5).equals("")) {
						a.setEquipModel(ls.get(5));
					}
					if (ls.get(6) != null && !ls.get(6).equals("")) {
						a.setEquipBrand(ls.get(6));
					}
					if (ls.get(7) != null && !ls.get(7).equals("")) {
						a.setUsePerson(ls.get(7));
					} else {
						a.setUsePerson(null);
					}
					if (ls.get(8) != null && !ls.get(8).equals("")) {
						a.setUseDepart(ls.get(8));
					}
					if (ls.get(9) != null && !ls.get(9).equals("")) {
						a.setEquipLocation(ls.get(9));
					} else {
						a.setEquipLocation(null);
					}
					if (ls.get(10) != null && !ls.get(10).equals("")) {
						a.setEquipAttach(ls.get(10));
					} else {
						a.setEquipAttach(null);
					}
			
					if (ls.get(11) != null && !ls.get(11).equals("")) {
						String temp = ls.get(11).replaceAll("/", "-");
						Date buyTime = sdf.parse(temp);
						a.setBuyTime(buyTime);
					}
					if (ls.get(12) != null && !ls.get(12).equals("")) {
						String temp = ls.get(12).replaceAll("/", "-");
						Date assignTime = sdf.parse(temp);
						a.setAssignTime(assignTime);
					} else {
						a.setAssignTime(null);
					}
					if (ls.get(13) != null && !ls.get(13).equals("")) {
						String temp = ls.get(13).replaceAll("/", "-");
						Date receiveTime = sdf.parse(temp);
						a.setReceiveTime(receiveTime);
					} else {
						a.setReceiveTime(null);
					}
					a.setModifyTime(new Date());
					a.setRemarks(ls.get(14));
					a.setIfPd((short) Integer.parseInt(ls.get(15)));

					assetService.insert(a);
					
					aote = new AssetOperate();
					aote.setOptePerson(loginUser.getName());
					aote.setOpteGenre(AssetOperate.OpteGenre.getValue("添加"));
					aote.setEquipIdentifier(a.getEquipIdentifier());
					aote.setEquipName(a.getEquipName());
					aote.setEquipModel(a.getEquipModel());
					aote.setEquipBrand(a.getEquipBrand());
					aote.setOpteTime(new Date());
					assetopteService.insertAssetOpte(aote);
					getSession().setAttribute("tip", "录入成功");
				}
			   }
				
				
				
			}

		} catch (Exception e) {
			e.printStackTrace();
			return "sysError";
		}
		return SUCCESS;
	}

	// 导出资产信息
	public String exportAssetExcel() {	
		try {
			List<Asset> assetList = assetService.listAll();
			String excelName = "资产信息表";
			Workbook wb = getAssetExcel(assetList, excelName);
			OutputStream out = getResponse().getOutputStream();
			wb.write(out);
			out.flush();
			out.close();
		} catch (Exception e) {
			e.printStackTrace();
			getSession().setAttribute("tip", "导出Excel失败");
			getSession().setAttribute("e", e.getMessage());
			return "sysError";
		}
		return null;
	}

	// 资产信息导出方法，供上面调用
	private Workbook getAssetExcel(List<Asset> assetList, String excelName) throws Exception {
		ArrayList<String> listTitle = new ArrayList<String>();
		listTitle.add("资产编号");
		listTitle.add("资产状态");
		listTitle.add("是否盘点");
		listTitle.add("设备类别");
		listTitle.add("设备名称");
		listTitle.add("设备型号");
		listTitle.add("设备品牌");
		listTitle.add("使用人员");
		listTitle.add("使用部门");
		listTitle.add("设备存放地点");
		listTitle.add("设备归属地点");
		listTitle.add("购买时间");
		listTitle.add("分配时间");
		listTitle.add("领用时间");
		listTitle.add("备注");
		Object[] oarr = listTitle.toArray();
		// HttpServletResponse response = ServletActionContext.getResponse();
		getResponse().setContentType("application/vnd.ms-excel;charset=UTF-8");
		if (getRequest().getHeader("User-Agent").toLowerCase().indexOf("firefox") > 0)// firefox浏览器
			excelName = new String(excelName.getBytes("UTF-8"), "ISO8859-1");
		else if (getRequest().getHeader("User-Agent").toLowerCase().indexOf("trident") > 0)// IE浏览器，ie11后请求头中的User-Agent中不再有"MSIE"
			excelName = URLEncoder.encode(excelName, "UTF-8");
		else if (getRequest().getHeader("User-Agent").toLowerCase().indexOf("chrome") > 0)// google浏览器
			excelName = new String(excelName.getBytes("UTF-8"), "ISO8859-1");
		// 转码防止乱码
		getResponse().addHeader("Content-Disposition", "attachment;filename=" + excelName + ".xls");
		List<POIExcelBaseBean> listRows = new ArrayList<POIExcelBaseBean>();
		SimpleDateFormat fd1 = new SimpleDateFormat("yyyy-MM-dd  HH:mm:ss");
		for (Asset a : assetList) {
			String equipIdentifier = "";
			String status = "";
			String ifPd = "";
			String equipGenre = "";
			String equipName = "";
			String equipModel = "";
			String equipBrand = "";
			String usePerson = "";
			String useDepart = "";
			String equipLocation = "";
			String equipAttach = "";
			String buyTime = "";
			String assignTime = "";
			String receiveTime = "";
			String remarks = "";

			if (a.getEquipIdentifier() != null) {
				equipIdentifier = a.getEquipIdentifier();
			}
			if (a.getStatus() != null) {
				status = Asset.Status.getName(a.getStatus());
			}
			if (a.getIfPd() != null) {
				ifPd = Asset.IfPd.getName(a.getIfPd());
			} else {
				ifPd = "";
			}
			if (a.getEquipGenre() != null) {
				equipGenre = Asset.EquipGenre.getName(a.getEquipGenre());
			}
			if (a.getEquipName() != null) {
				equipName = a.getEquipName();
			}
			if (a.getEquipModel() != null) {
				equipModel = a.getEquipModel();
			}
			if (a.getEquipBrand() != null) {
				equipBrand = a.getEquipBrand();
			}
			if (a.getUsePerson() != null) {
				usePerson = a.getUsePerson();
			}
			if (a.getUseDepart() != null) {
				useDepart = a.getUseDepart();
			}
			if (a.getEquipLocation() != null) {
				equipLocation = a.getEquipLocation();
			}
			if (a.getEquipAttach() != null) {
				equipAttach = a.getEquipAttach();
			}
			if (a.getBuyTime() != null) {
				buyTime = fd1.format(a.getBuyTime());
			}
			if (a.getAssignTime() != null) {
				assignTime = fd1.format(a.getAssignTime());
			} else {
				assignTime = "";
			}
			if (a.getReceiveTime() != null) {
				receiveTime = fd1.format(a.getReceiveTime());
			} else {
				receiveTime = "";
			}
			remarks = a.getRemarks();

			listRows.add(new POIExcelAssetBean(equipIdentifier, status, ifPd, equipGenre, equipName, equipModel,
					equipBrand, usePerson, useDepart, equipLocation, equipAttach, buyTime,assignTime, receiveTime, remarks));
		}
		return POIExcelUtils.OutputExcel(oarr, listRows, 1, null, null);
	}

	// 查询部门
	public String listDepartmentArr1() {
		departmentList = departService.listDepart(departQueryName);
		departmentArr = new JSONArray();
		for (Department department : departmentList) {
			if (departQueryName == null) {
				if (department.getName().contains("_") == false) {
					departmentArr.add(department);
				}
			} else {
				String parent_[] = departQueryName.split("_");
				String chird_[] = department.getName().split("_");
				if (parent_.length == chird_.length - 1) {
					departmentArr.add(department);
				}
			}
		}
		return SUCCESS;
	}

	// getDepartTree
	public String listDepartmentArr() {
		departmentList = departService.listDepart(null);
		departmentArr = new JSONArray();
		for (int i = 4; i >= 2; i--) {
			Map<String, String> releationShip = getDepartmentBy(i, departmentList, departmentArr);
			departmentArr = createNode(releationShip, departmentArr);
		}
		for (Department department : departmentList) {
			List<Department> departmentSingleList = departService.listDepart(department.getName());
			if (departmentSingleList.size() == 1 && !departmentSingleList.get(0).getName().contains("_")) {
				JSONObject departmentJson = new JSONObject();
				departmentJson.put("name", department.getName());
				departmentArr.add(departmentJson);
			}
		}
		return SUCCESS;
	}

	// 依据层次结构获取，得到父级目录以及子目录的对应关系，产生 key和value的键值对,并且找到孩子节点
	private Map<String, String> getDepartmentBy(int level, List<Department> departments, JSONArray childNode) {
		Map<String, String> fiterDepartments = new HashMap<String, String>();
		for (Department department : departments) {
			String[] ss = department.getName().split("_");
			if (ss.length >= level) {
				boolean flag = false;
				// 1.孩子节点和上级节点的关系
				fiterDepartments.put(ss[level - 1], ss[level - 2]);
				for (Object obj : childNode) {
					// 如果已经构建的树是上一级的子节点，则把子节点和父节点的关系联系起来
					JSONObject node = (JSONObject) obj;
					if (node.getString("name").equals(ss[level - 1])) {
						// JSONObject parentNode = new JSONObject();
						// parentNode.put("name",ss[level-1]);
						// parentNode.put("children",);
						flag = true;
					}
				}
				// 2.如果上一级的节点中不存在，该节点，则在孩子节点中新增节点
				if (flag == false) {
					JSONObject cObj = new JSONObject();
					cObj.put("name", ss[level - 1]);
					childNode.add(cObj);
				}
			}
		}
		return fiterDepartments;
	}

	private JSONArray createNode(Map<String, String> filiation, JSONArray children) {
		JSONArray nodes = new JSONArray();
		Set<String> parentString = new HashSet<String>();
		// 获取父节点
		for (String fv : filiation.values()) {
			parentString.add(fv);
		}
		// 将父节点和子节点进行对应
		for (String p : parentString) {
			JSONObject parentNode = new JSONObject();
			parentNode.put("name", p);
			JSONArray child = new JSONArray();
			Set set = filiation.entrySet();
			Iterator it = set.iterator();
			while (it.hasNext()) {
				Map.Entry entry = (Map.Entry) it.next();
				if (entry.getValue().equals(p)) {
					// 将子节点装入的父节点下
					for (Object c : children) {
						JSONObject cObj = (JSONObject) c;
						String name = cObj.getString("name");
						if (entry.getKey().equals(name)) {
							child.add(c);
						}
					}
					// 装入子节点
					if (child.size() > 0) {
						parentNode.put("children", child);
					}
				}
			}
			nodes.add(parentNode);
		}
		return nodes;
	}

	public String getText() {
		return text;
	}

	public void setText(String text) {
		this.text = text;
	}

	public OutputStream getOutput() {
		return output;
	}

	public void setOutput(OutputStream output) {
		this.output = output;
	}

	public File getFile() {
		return file;
	}

	public void setFile(File file) {
		this.file = file;
	}

	public String getFileName() {
		return fileName;
	}

	public void setFileName(String fileName) {
		this.fileName = fileName;
	}

	public List<Asset> getAssetLists() {
		return assetLists;
	}

	public void setAssetLists(List<Asset> assetLists) {
		this.assetLists = assetLists;
	}

	public Asset getAsset() {
		return asset;
	}

	public void setAsset(Asset asset) {
		this.asset = asset;
	}

	public User getLoginUser() {
		return loginUser;
	}

	public void setLoginUser(User loginUser) {
		this.loginUser = loginUser;
	}

	public AssetOperate getAote() {
		return aote;
	}

	public void setAote(AssetOperate aote) {
		this.aote = aote;
	}

	public AssetUseHistory getAssetUseHistory() {
		return assetUseHistory;
	}

	public void setAssetUseHistory(AssetUseHistory assetUseHistory) {
		this.assetUseHistory = assetUseHistory;
	}

	public List<AssetUseHistory> getAssetUseHistoryList() {
		return assetUseHistoryList;
	}

	public void setAssetUseHistoryList(List<AssetUseHistory> assetUseHistoryList) {
		this.assetUseHistoryList = assetUseHistoryList;
	}

	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public Short getOptestate() {
		return optestate;
	}

	public void setOptestate(Short optestate) {
		this.optestate = optestate;
	}
	
	public Short getState() {
		return state;
	}

	public void setState(Short state) {
		this.state = state;
	}

	public Date getReceiveTime() {
		return receiveTime;
	}

	public void setReceiveTime(Date receiveTime) {
		this.receiveTime = receiveTime;
	}

	public Date getRevertTime() {
		return revertTime;
	}

	public void setRevertTime(Date revertTime) {
		this.revertTime = revertTime;
	}

	public String getIds() {
		return ids;
	}

	public void setIds(String ids) {
		this.ids = ids;
	}

	public String getEquipIdentifier() {
		return equipIdentifier;
	}

	public void setEquipIdentifier(String equipIdentifier) {
		this.equipIdentifier = equipIdentifier;
	}

	public String getItCode() {
		return itCode;
	}

	public void setItCode(String itCode) {
		this.itCode = itCode;
	}

	public String getOperaRes() {
		return operaRes;
	}

	public void setOperaRes(String operaRes) {
		this.operaRes = operaRes;
	}

	public String[] getCheckedIds() {
		return checkedIds;
	}

	public void setCheckedIds(String[] checkedIds) {
		this.checkedIds = checkedIds;
	}

	public List<String> getQRcodeUrl() {
		return QRcodeUrl;
	}

	public void setQRcodeUrl(List<String> qRcodeUrl) {
		QRcodeUrl = qRcodeUrl;
	}

	public String getTemp() {
		return temp;
	}

	public void setTemp(String temp) {
		this.temp = temp;
	}

	public List<Asset> getPdLists() {
		return pdLists;
	}

	public void setPdLists(List<Asset> pdLists) {
		this.pdLists = pdLists;
	}

	public List<Asset> getUnPdLists() {
		return unPdLists;
	}

	public void setUnPdLists(List<Asset> unPdLists) {
		this.unPdLists = unPdLists;
	}

	public int getPdStatus() {
		return pdStatus;
	}

	public void setPdStatus(int pdStatus) {
		this.pdStatus = pdStatus;
	}

	public int getPageSizeALL() {
		return pageSizeALL;
	}

	public void setPageSizeALL(int pageSizeALL) {
		this.pageSizeALL = pageSizeALL;
	}

	public int getPageSizeCurr() {
		return pageSizeCurr;
	}

	public void setPageSizeCurr(int pageSizeCurr) {
		this.pageSizeCurr = pageSizeCurr;
	}

	public int getPageNumAll() {
		return pageNumAll;
	}

	public void setPageNumAll(int pageNumAll) {
		this.pageNumAll = pageNumAll;
	}

	public int getQuerySum() {
		return querySum;
	}

	public void setQuerySum(int querySum) {
		this.querySum = querySum;
	}

	public static int getPigeNum() {
		return pigeNum;
	}

	public static void setPigeNum(int pigeNum) {
		AssetAction.pigeNum = pigeNum;
	}

	public List<Integer> getPagingArr() {
		return pagingArr;
	}

	public void setPagingArr(List<Integer> pagingArr) {
		this.pagingArr = pagingArr;
	}

	public Integer getStart() {
		return start;
	}

	public void setStart(Integer start) {
		this.start = start;
	}

	public Integer getLength() {
		return length;
	}

	public void setLength(Integer length) {
		this.length = length;
	}

	public Integer getDraw() {
		return draw;
	}

	public void setDraw(Integer draw) {
		this.draw = draw;
	}

	public Map<String, Object> getDataMap() {
		return dataMap;
	}

	public void setDataMap(Map<String, Object> dataMap) {
		this.dataMap = dataMap;
	}

	public String getIdentifer() {
		return identifer;
	}

	public void setIdentifer(String identifer) {
		this.identifer = identifer;
	}

	public AssetWeb getAssetWeb() {
		return assetWeb;
	}

	public void setAssetWeb(AssetWeb assetWeb) {
		this.assetWeb = assetWeb;
	}

	public Short getEquipGenre() {
		return equipGenre;
	}

	public void setEquipGenre(Short equipGenre) {
		this.equipGenre = equipGenre;
	}

	public Short getStatus() {
		return status;
	}

	public void setStatus(Short status) {
		this.status = status;
	}

	public Date getBuyTime1() {
		return buyTime1;
	}

	public void setBuyTime1(Date buyTime1) {
		this.buyTime1 = buyTime1;
	}

	public Date getBuyTime2() {
		return buyTime2;
	}

	public void setBuyTime2(Date buyTime2) {
		this.buyTime2 = buyTime2;
	}

	public Date getUseTime1() {
		return useTime1;
	}

	public void setUseTime1(Date useTime1) {
		this.useTime1 = useTime1;
	}

	public Date getUseTime2() {
		return useTime2;
	}

	public void setUseTime2(Date useTime2) {
		this.useTime2 = useTime2;
	}

	public String getUrl() {
		return url;
	}

	public void setUrl(String url) {
		this.url = url;
	}

	public String getQueryUserName() {
		return queryUserName;
	}

	public void setQueryUserName(String queryUserName) {
		this.queryUserName = queryUserName;
	}

	public List<User> getUserList() {
		return userList;
	}

	public void setUserList(List<User> userList) {
		this.userList = userList;
	}

	public JSONArray getJsonArray() {
		return jsonArray;
	}

	public void setJsonArray(JSONArray jsonArray) {
		this.jsonArray = jsonArray;
	}

	public JSONObject getJsonObject() {
		return jsonObject;
	}

	public void setJsonObject(JSONObject jsonObject) {
		this.jsonObject = jsonObject;
	}

	public Long getUserId() {
		return userId;
	}

	public void setUserId(Long userId) {
		this.userId = userId;
	}

	public JSONArray getDepartmentArr() {
		return departmentArr;
	}

	public void setDepartmentArr(JSONArray departmentArr) {
		this.departmentArr = departmentArr;
	}

	public String getDepartQueryName() {
		return departQueryName;
	}

	public void setDepartQueryName(String departQueryName) {
		this.departQueryName = departQueryName;
	}

	public JSONObject getOperaRem() {
		return operaRem;
	}

	public void setOperaRem(JSONObject operaRem) {
		this.operaRem = operaRem;
	}	
}
